﻿using BaseFramework;
using BaseFramework.Core;
using BaseFramework.DbConnectionProvider;
using LiteFramework.Contract;
using System;
using System.Linq;
using System.Collections.Generic;

namespace LiteFramework.Server.Component
{
    public class RoleComponent : AbsComponent<LiteFramework.Model.Role>, IRoleContract
    {
        public RoleComponent(IDbConnectionProvider connectionProvider = null)
            : base(connectionProvider)
        { }

        public LiteFramework.Model.Role GetDefaultRole() { return null; }

        public override void beforeUpdate(Model.Role model, CancelEventExArgs e)
        {
            base.beforeUpdate(model, e);
            if (!e.Cancel)
            {
                if (model.IsSystem)
                {
                    e.Cancel = true;
                    e.Error = "不允许修改系统内置角色";
                }
            }
        }
        public override void beforeDelete(Model.Role model, CancelEventExArgs e)
        {
            base.beforeDelete(model, e);
            if (!e.Cancel)
            {
                if (model.IsSystem)
                {
                    e.Cancel = true;
                    e.Error = "不允许删除系统内置角色";
                }
            }
        }

        public IList<LiteFramework.Model.Task> GetRoleTasks(string roleId)
        {
            IExpression expression = Expression.Sql(DefaultValue.RootTableHolder + ".Id IN (SELECT RightId FROM SYS_RolesInRights WHERE RoleId='" + roleId + "')");
            return PersistentEntityMediator<LiteFramework.Model.Task>.GetList(connectionProvider, expression, new OrderParam("Seq", "Group", "SubSeq"));
        }
        public IList<LiteFramework.Model.Task> GetUserTasks(int userId)
        {
            IExpression expression = Expression.Sql(DefaultValue.RootTableHolder + ".Id IN (SELECT RightId FROM SYS_RolesInRights WHERE RightId IN (SELECT RightId FROM SYS_UsersInRoles WHERE UserId='" + userId + "'))");
            return PersistentEntityMediator<LiteFramework.Model.Task>.GetList(connectionProvider, expression, new OrderParam("Seq", "Group", "SubSeq"));
        }

        public IList<LiteFramework.Model.User> GetRoleUsers(string roleId)
        {
            IExpression expression = Expression.Sql(DefaultValue.RootTableHolder + ".Id IN (SELECT RightId FROM SYS_RolesInRights WHERE RoleId='" + roleId + "')");
            return ServerApplication.ComponentFactory.Create<IUserContract>().GetList(expression);
        }

        public IList<LiteFramework.Model.Role> GetUserRoles(int userId)
        {
            IExpression expression = Expression.Sql(DefaultValue.RootTableHolder + ".Id IN (SELECT RoleId FROM SYS_UsersInRoles WHERE UserId='" + userId + "')");
            return PersistentEntityMediator<LiteFramework.Model.Role>.GetList(connectionProvider, expression);
        }
    }
}